//
//  JobRecommendListViewController.m
//  CYWFrame
//
//  Created by oldfish on 2018/8/10.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "JobRecommendListViewController.h"
#import "NetworkTool.h"
#import "JobTableViewCell.h"
#import "ApplicantTableViewCell.h"
#import "JobInfoForRecruitIndex.h"
#import "JobDetailViewController.h"
#import "PreviewResumeViewController.h"


@interface JobRecommendListViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) UIImageView *backgroundImage;
@end

@implementation JobRecommendListViewController

-(void)viewWillAppear:(BOOL)animated
{
	[self getJobInfo];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	self.page = 1;
	[self buildUI];
	[self refreshData];
	
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)buildUI{
	_jobListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, self.view.height-130) style:UITableViewStylePlain];
	[_jobListTableView registerClass:[JobTableViewCell class] forCellReuseIdentifier:@"JobCell"];
	[_jobListTableView registerNib:[UINib nibWithNibName:@"ApplicantTableViewCell" bundle:nil] forCellReuseIdentifier:@"ApplicantCell"];
	_jobListTableView.backgroundColor = UISeparatedColorRGB;
	_jobListTableView.delegate = self;
	_jobListTableView.dataSource = self;
	_jobListTableView.scrollEnabled = NO;
    _jobListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	
	if (@available(iOS 11.0, *)) {
		_jobListTableView.estimatedRowHeight = 0;
		_jobListTableView.estimatedSectionFooterHeight = 0.;
		_jobListTableView.estimatedSectionHeaderHeight = 0.;
		_jobListTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
		_jobListTableView.contentInset = UIEdgeInsetsMake(0,0,70,0);//64和49自己看效果，是否应该改成0
		_jobListTableView.scrollIndicatorInsets = _jobListTableView.contentInset;
	} else {
		// Fallback on earlier versions
	}
	
	if ([GetUserDefaule(USERINFO)[@"role"] isEqualToString:@"5"] ||
		[GetUserDefaule(USERINFO)[@"role"] isEqualToString:@"6"])
	{
		_jobListTableView.rowHeight = 125;
	}
	else
	{
		_jobListTableView.rowHeight = 170;
	}
	[self.view addSubview:_jobListTableView];
	_backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-234/2, 80, 234, 222)];
	[_backgroundImage setImage:IMAGE(@"no_job_data")];
	[_jobListTableView addSubview:_backgroundImage];
}

- (void)getJobInfo
{
	if (!self.keyword) {
		self.keyword = @"";
	}
	if (!self.category_id) {
		self.category_id = @"";
	}
	if (!self.district) {
		self.district = @"";
	}
	NSDictionary *param = @{
                            @"page_size":@"10",
                            @"page_number":[NSString stringWithFormat:@"%ld", self.page],
                            @"keyword":self.keyword,
                            @"district":self.district,
                            @"category_id":self.category_id,
                            };
	[[NetworkTool sharedTool] requestWithName:@"获取岗位/人才信息" URLString:APIRecruitIndex parameters:param method:@"GET" callBack:^(id responseObject) {
		
		//NSError *error = nil;
		
		NSArray *array = responseObject[@"data"];
		if (self.page == 1) {
			[self.jobArray removeAllObjects];
			NSNotification *notice = [NSNotification notificationWithName:@"endJobRefresh" object:nil userInfo:@{}];
			[[NSNotificationCenter defaultCenter] postNotification:notice];
		}
		
		if (array.count == 0) {
			self.page--;
			if (self.page == 0) {
				self.page = 1;
			}
		}
		for (NSDictionary *dict in array)
		{
			JobInfoForRecruitIndex *jobInfo = [[JobInfoForRecruitIndex alloc] init];
			[jobInfo setValuesForKeysWithDictionary:dict];
			[self.jobArray addObject:jobInfo];
		}
		if (_jobArray.count) {
			NSLog(@"职位信息是%@",_jobArray);
			NSLog(@"有%ld个数据", _jobArray.count);
			self.backgroundImage.hidden = YES;
		}
		else {
			NSLog(@"没有职位信息");
			self.backgroundImage.hidden = NO;
		}
		dispatch_async(dispatch_get_main_queue(), ^{
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[self.jobListTableView.mj_footer endRefreshing];
			[self.jobListTableView.mj_header endRefreshing];
			[self.jobListTableView reloadData];
			
			[UIView animateWithDuration:0.5 animations:^{
				UIEdgeInsets inset = UIEdgeInsetsMake(0,0,70,0);
				self.jobListTableView.contentInset = inset;
				//[self.jobListTableView setContentOffset:CGPointMake(0, 125) animated:NO];
			} completion:^(BOOL finished) {
			}];
		});
	}];
}
#pragma mark ==========更新数据==========
- (void)refreshData {
	__weak typeof (self) weakSelf = self;
	
	/*
	_jobListTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
		NSLog(@"下拉刷新");
		weakSelf.page = 1;
		[weakSelf getJobInfo];
	}];
	*/
	
	_jobListTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
		NSLog(@"上拉加载");
		weakSelf.page++;
		[weakSelf getJobInfo];
	}];
}

//TableView delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([GetUserDefaule(USERINFO)[@"role"] isEqualToString:@"5"] ||
		[GetUserDefaule(USERINFO)[@"role"] isEqualToString:@"6"])
	{
		ApplicantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ApplicantCell"];
		NSLog(@"my role is %@", GetUserDefaule(USERINFO)[@"role"]);
		if (self.jobArray.count > indexPath.row) {
			[cell setJobInfo:self.jobArray[indexPath.row]];
			NSLog(@"求职者名称：%@", cell.name.text);
		}
		return cell;
	}
	else
	{
		JobTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JobCell"];
		if (!cell) {
			// 创建cell,并指定样式和添加重用标识
			cell = [[JobTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"JobCell"];
		}
		NSLog(@"my role is %@", GetUserDefaule(USERINFO)[@"role"]);
		if (self.jobArray.count > indexPath.row) {
			[cell setJobInfo:self.jobArray[indexPath.row]];
			NSLog(@"公司名称：%@", cell.companyName.text);
		}
		return cell;
	}
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *role = GetUserDefaule(USERINFO)[@"role"];
	/*
	if ([role integerValue] == 0) {
		[self presentViewController:[LZCTools alertMessage:@"请先登录"] animated:YES completion:nil];
	}
	 */
	if ([role isEqualToString:@"5"] ||
		[role isEqualToString:@"6"]) {
		PreviewResumeViewController *resumeVC = [[PreviewResumeViewController alloc] init];
		JobInfoModel *jobInfo = self.jobArray[indexPath.row];
		resumeVC.resumeId = jobInfo.resume_id;
		resumeVC.shouldShowInviteBtn = 1;
		[self.navigationController pushViewController:resumeVC animated:YES];
		
	}
	else
	{
		JobDetailViewController *detail = [[JobDetailViewController alloc] init];
		JobInfoModel *jobInfo = self.jobArray[indexPath.row];
		detail.position_id = jobInfo.position_id;
		detail.shouldHideDeliverBtn = 0;
		[self.navigationController pushViewController:detail animated:YES];
	}
	
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [self.jobArray count];
	
}

- (NSMutableArray *)jobArray
{
	if (!_jobArray) {
		_jobArray = [[NSMutableArray alloc] init];
	}
	return _jobArray;
}

- (void)setKeyword:(NSString *)keyword
{
	if (_keyword != keyword) {
		_keyword = keyword;
	}
	self.page = 1;
	[self getJobInfo];
}

- (void)setDistrict:(NSString *)district
{
	if (_district != district) {
		_district = district;
	}
	self.page = 1;
	[self getJobInfo];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	
	if (scrollView.contentOffset.y < -10) {
		NSNotification *notice = [NSNotification notificationWithName:@"returnTop" object:nil userInfo:@{}];
		[[NSNotificationCenter defaultCenter] postNotification:notice];
	}
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
